package com.yswy.app.authfilter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yswy.app.annotation.NotAuth;
import com.yswy.app.service.AppUserService;
import com.yswy.app.service.UserWxOpenService;
import com.yswy.common.enums.ResultStatus;
import com.yswy.common.exception.LoginException;
import com.yswy.common.exception.WxLoginException;
import com.yswy.common.model.ResultModel;
import com.yswy.domain.entity.AppUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import springfox.documentation.schema.ModelRef;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@WebFilter(filterName = "AuthFilter", urlPatterns = "/*")
public class AuthFilter implements Filter {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    public static final String ROOT = "4e92a3c21aa46fe075f0965d939090b9";

    private static final String CONNECTOR = "/";

    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList(
                    "/config/getConFigByType",//获取常量
                    "/config/getConFigByTypeList",//获取常量
                    "/packge/getForcePackage",//获取更新包
                    "/sso/login",//登录
                    "/sso/loginApp",//登录

                    "/sso/sendCode",//发送验证码
                    "/sso/updateUserDevice",
                    "/sso/wxOauth",
                    "/sso/getOpenlink",
                    "/sso/addOpenlink",
//                    "/management/getList",//获取个人中心菜单列表
                    "/config/getConFigByTypeList",
                    "/tg/handleCallback",
                    "/tg/delDeduction",
                    "/tg/ksCallback",
                    "/tg/saveUserJlAdLog",
                    "/payOrder/testPayAgreement",
                    "/payOrder/callbackOrder",
                    "/payOrder/callbackAgreement",
                    "/payOrder/callbackWXYwPayOrder",
                    "/payOrder/callbackZfbYwPayOrder",
                    "/payOrder/zfbCallback",
                    "/payOrder/wechatPayNotify",
//                    "/pollingImg/pollingImgList",
                    "/payOrder/testIsDeduction",
                    "/theater/hotSearch",
                    "/theater/search",
                    "/theater/listTheaterPlayType",
                    "/theater/getTheaterPlayByType",
                    "/upload/addTheaterPlay",
                    "/upload/addPack",
                    "/upload/addPacketTemplate",
                    "/upload/addTheaterPlayByCsj",

                    "/qyCard/backFlCardOrderJzy",
                    "/payOrder/callbackZfbYwPayOrder",
                    "/qyCard/backYlyCardOrder"
//                    "/theater/getTheaterPlayByType"
            )));

    @Resource
    private AppUserService appUserService;
    @Resource
    private UserWxOpenService userWxOpenService;

    @Override
    public void init(FilterConfig config) throws ServletException {
        log.info("授权过滤器初始化!");

        ServletContext context = config.getServletContext();
        log.info("不需要认证的 URI：");
        for (String d : ALLOWED_PATHS) {
            log.info(d);
        }
//        permissionMap = ssoService.getAllModelPermission();
//        log.info("权限表：" + permissionMap);

    }

    @Override
    public void destroy() {
        log.info("授权过滤器注销!");
    }


//    @Override
//    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
//            throws IOException, ServletException {
//        HttpServletRequest req = (HttpServletRequest) request;
//        HttpServletResponse res = (HttpServletResponse) response;
//        //跨域设置
//        cros(res);
//        res.setCharacterEncoding("UTF-8");
//        res.setContentType("application/json; charset=utf-8");
//        res.setStatus(HttpServletResponse.SC_OK);
//        chain.doFilter(req, res);
//    }



    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ObjectMapper mapper = new ObjectMapper();
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String reqAddress = request.getRemoteAddr();

        String channle = req.getHeader("channle");
        String version = req.getHeader("version");
        log.info(reqAddress + " 安全过滤器：" + req.getRequestURI()
                + " METHOD:" + req.getMethod()
                +" channle:" +channle
                +" version:" +version);
        String requestURI = req.getRequestURI();
//        log.info(requestURI);
        boolean allowedPath = ALLOWED_PATHS.contains(requestURI);
        //跨域设置
        cros(res);
        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json; charset=utf-8");
        res.setStatus(HttpServletResponse.SC_OK);
        String[] strs = requestURI.split("/");
        String token = "";
        AppUser user = null;
        if (req.getRequestURI().contains("swagger")
                || req.getRequestURI().contains("api")
                || req.getRequestURI().contains("druid")
                || allowedPath) {
            chain.doFilter(req, res);
            return;
        }
        if (strs.length >= 2) {
            token = req.getHeader("Authorization");
            log.info(reqAddress + " Authorization : " + token);
            //更新用户的TOKEN 过期时间，这样用户只要一直有操作，就永远不需要登录。
            try{
                user = appUserService.getUserByAuthToken(token);
            }catch (LoginException e){
                res.getWriter().write(mapper.writeValueAsString(ResultModel.error(ResultStatus.LOGIN_OVER)));
                return;
            }

            //判断是否微信授权
//            try{
//                userWxOpenService.isOauthThrow(user.getId());
//            }catch (WxLoginException e){
//                res.getWriter().write(mapper.writeValueAsString(ResultModel.error(ResultStatus.WX_OVER)));
//                return;
//            }
            if (user!= null){
                req.getSession().setAttribute("user", user);
            }
        }
        if (StringUtils.isNotBlank(token)) {
            //如果是管理员登录直接跳过验证
            if (ROOT.equals(token) || user != null) {
                chain.doFilter(req, res);
                return;
            }
        }
        if (user == null) {
            res.getWriter().write(mapper.writeValueAsString(ResultModel.error(ResultStatus.LOGIN_OVER)));
        } else {
            res.getWriter().write(mapper.writeValueAsString(ResultModel.error("用户没有正确权限")));
        }
    }

    private HttpServletResponse cros(HttpServletResponse res) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "3600");
//        res.setHeader("Access-Control-Allow-Headers", "*");
//        res.setHeader("Authorization", "Authorization");
        res.setHeader("Content-Type","application/json; charset=utf-8");
        res.setHeader("Access-Control-Allow-Headers", "authorization,Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,*");
        res.setStatus(HttpServletResponse.SC_OK);
        return res;
    }

}
